Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Datatypes

Python Dictionary

Dictionaries: Unordered Collections of Key-Value Pairs

A dictionary in Python is a fundamental data structure used to store key-value pairs. Dictionaries are powerful because they allow you to associate unique labels (keys) with specific values. Key features of dictionaries include: Unordered: Unlike lists or tuples, the order of items in a dictionary is not guaranteed. You access items using their keys rather than their positions. Mutable: You can add, remove, and change key-value pairs in a dictionary after its creation. Unique Keys: Each key in a dictionary must be unique and immutable. Immutable data types (strings, integers, tuples) are commonly used as keys. Heterogeneous: Values in a dictionary can be of any data type, including numbers, strings, lists, or even other dictionaries. This flexibility allows you to model complex data relationships.

Creating Dictionaries

You create dictionaries using curly braces {}. Key-value pairs are separated by colons :, and multiple pairs are separated by commas ,:
Python dictionary structure and basic examples # Example dictionaries student = { "name": "Alice", "age": 25, "courses": ["Math", "History", "Computer Science"], } phone_numbers = { "John": "555-1212", "Jane": "555-3434" } empty_dict = {} # Empty dictionary print(student) print(phone_numbers) print(empty_dict)

Output

{'name': 'Alice', 'age': 25, 'courses': ['Math', 'History', 'Computer Science']} {'John': '555-1212', 'Jane': '555-3434'} {}

Accessing and Modifying Values

Access by Key: To retrieve a value from a dictionary, use its key inside square brackets []:
Access valuesstudent_name = student["name"] # Accesses "Alice" course = student["courses"][0] # Accesses "Math" (first course)
Adding a new key-value pair:
Adding key-value pairphone_numbers["Bob"] = "555-5656" # Adds Bob's phone number
Modifying an existing value:
Modifying valuestudent["age"] = 26 # Updates Alice's age
Deleting a key-value pair: Use the del keyword:
Deleting a valuedel student["courses"]

Common Operations

Membership Testing (in): Check if a key exists in the dictionary. Length (len): Get the number of key-value pairs in the dictionary. Iterating over Keys: Use a for loop to iterate through keys. .items(): Get key-value pairs as tuples. .keys(): Get all keys. .values(): Get all values. examples for the six dictionary operations mentioned above, using the provided product dictionary:
Example of common operations in python dictionary product = { "name": "Laptop", "brand": "XYZ", "price": 799.99, "specifications": { "processor": "Intel i7", "RAM": "16 GB", "storage": "512 GB SSD" } } #1. Membership Testing (in): # Check if a key exists if "brand" in product: print("The 'brand' key exists.") else: print("The 'brand' key does not exist.") #2. Length (len): # Get the number of key-value pairs number_of_items = len(product) print(f"\n The dictionary has {number_of_items} items.") #3. Iterating over Keys: # Print all keys using a for loop print("\nprinting using for loop") for key in product: print(key) #4. .items(): # Get key-value pairs as tuples item_tuples = product.items() print("\nKey value pairs as tuples : ",item_tuples) #5. .keys(): # Get all keys as a dictionary view all_keys = product.keys() print("\nGetting all keys : ",all_keys) #6. .values(): # Get all values as a dictionary view all_values = product.values() print("\n All values : ",all_values)

Output

The 'brand' key exists. The dictionary has 4 items. printing using for loop name brand price specifications Key value pairs as tuples : dict_items([('name', 'Laptop'), ('brand', 'XYZ'), ('price', 799.99), ('specifications', {'processor': 'Intel i7', 'RAM': '16 GB', 'storage': '512 GB SSD'})]) Getting all keys : dict_keys(['name', 'brand', 'price', 'specifications']) All values : dict_values(['Laptop', 'XYZ', 799.99, {'processor': 'Intel i7', 'RAM': '16 GB', 'storage': '512 GB SSD'}])
These examples demonstrate how to use each operation for the given dictionary. Remember that the output might change depending on the modifications you make to the dictionary.

Example of manupulating Dictionary

Example for Access,Edit,Add and delete values in python dictionary product = { "name": "Laptop", "brand": "XYZ", "price": 799.99, "specifications": { "processor": "Intel i7", "RAM": "16 GB", "storage": "512 GB SSD" } } #Accessing values #Use the key within square brackets [] to access the corresponding value. #For nested dictionaries, access nested values using a chain of keys. # Accessing brand and processor print(f"Brand: {product['brand']}") # Access brand using key print(f"Processor: {product['specifications']['processor']}") # Access nested value #Changing Values: #Assign a new value to the existing key to modify it. #For nested dictionaries, use chained indexing to reach the specific value. # Update price and RAM product["price"] = 849.99 # Update price product["specifications"]["RAM"] = "32 GB" # Update RAM in nested dictionary print("\nAfter updating values : \n",product) #Adding a New Key-Value Pair: #Use the assignment operator (=) to create a new key-value pair. # Add a discount key-value pair product["discount"] = 50 print("\nAfter Adding a key value pair : \n",product) #Removing a Key-Value Pair: #Use the del keyword followed by the key within square brackets. # Remove the entire "specifications" dictionary del product["specifications"] print("\nAfter deleting value : \n",product)

Output

Brand: XYZ Processor: Intel i7 After updating values : {'name': 'Laptop', 'brand': 'XYZ', 'price': 849.99, 'specifications': {'processor': 'Intel i7', 'RAM': '32 GB', 'storage': '512 GB SSD'}} After Adding a key value pair : {'name': 'Laptop', 'brand': 'XYZ', 'price': 849.99, 'specifications': {'processor': 'Intel i7', 'RAM': '32 GB', 'storage': '512 GB SSD'}, 'discount': 50} After deleting value : {'name': 'Laptop', 'brand': 'XYZ', 'price': 849.99, 'discount': 50}

Built-in Methods:

clear() - Removes all the elements from the dictionary copy() - Returns a copy of the dictionary fromkeys() - Returns a dictionary with the specified keys and value get() - Returns the value of the specified key items() - Returns a list containing a tuple for each key value pair keys() - Returns a list containing the dictionary's keys pop() - Removes the element with the specified key popitem() - Removes the last inserted key-value pair setdefault() - Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() - Updates the dictionary with the specified key-value pairs values() - Returns a list of all the values in the dictionary Dictionaries are highly versatile in Python and find applications across various domains: ✦ Representing structured data: Store attributes of objects like a product (name, price, description), or a person (name, age, occupation). ✦ Building lookup tables: Create fast key-based lookups. For example, a dictionary to map country codes to country names. ✦ Counting the frequency of elements: Keep track of how many times items appear in a dataset (e.g., word frequency in a text).

Summary

Creation: A dictionary can be created by enclosing a comma-separated list of key-value pairs in curly braces {}. For example, {'Name': 'John', 'Age': 30} is a dictionary with two key-value pairs. You can also create a dictionary using the built-in dict() function. ✦ Accessing Values: Values in a dictionary can be accessed using their corresponding keys. For example, if d is a dictionary, you can access the value associated with the key 'Name' using d['Name']. ✦ Key Characteristics: Keys in a dictionary must be immutable, which means you can use strings, numbers, or tuples as dictionary keys. However, lists or other dictionaries cannot be used as keys because they are mutable. ✦ Value Characteristics: Values in a dictionary can be of any type, and they can be modified, which means a dictionary is a mutable data type. ✦ Built-in Methods: Python provides several built-in methods for dictionaries, such as get(), items(), keys(), values(), pop(), popitem(), and update(). ✦ Nested Dictionaries: A dictionary can contain another dictionary, which means dictionaries can be nested. Remember, dictionaries in Python are used to store data that are related, such as the information contained in an ID or a user profile. They are very similar to what, in other programming languages, is called an associative array.

  📌TAGS

★python ★ datatypes ★ dictionary

Tutorials